<?php
/* +----------------------------------------------------------------------
 * 作	   者: xinglou <xinglou1@foxmail.com>
 +----------------------------------------------------------------------
 * 创建日期：2015-06-24
 +----------------------------------------------------------------------
 * 文件描述：系统页面管理
 +----------------------------------------------------------------------
 * 升级记录： 
 +----------------------------------------------------------------------
*/
class FormAction extends CommonAction {
	
	/**
	 * 问卷答题界面
	 */
	public function item(){
		$model = new FormModel();
		$item_value_model = new ItemValueModel();
		$formid = $this->_request('formid');
		$userid = $model->getOperator();
		$item_value = $item_value_model->where('formid = ".$formid." and operator = ".$userid."');
		/* if(!empty($item_value)){
			$this->error("你已经做过次问卷了", __APP__."?g=Index&m=Form&a=view&formid=".$formid);
		} */
		//dump($formid);
		$this->assign("formid",$formid);
		$test_data = $model->field('id, title, intro, item_info, status')
						   ->where("id = '".$formid."'")
						   ->find();
		//dump($test_data);
		if(!empty($test_data['item_info'])) {
			$item_info = array();
			$item_info = explode(',', $test_data['item_info']);
			foreach($item_info as $key => $value) {
				//根据模块类型获取模块内容
				$item_info_detail = explode(':', $value);
				switch ($item_info_detail[0]) {
					case 'select' :
						//dump($item_info_detail[1]);
						$data = R('Admin/QuestionTestSelect/get_item_edit', array($item_info_detail[1]));
						$data["question"] = $this->filterHtml($data["question"]);
						break;
					case 'desc' :
						//dump($item_info_detail[1]);
						$data = R('Admin/QuestionTestDesc/get_item_edit',array($item_info_detail[1]));
						break;
					case 'judge' :
						//dump($item_info_detail[1]);
						$data = R('Admin/QuestionTestJudge/get_item_edit',array($item_info_detail[1]));
						break;
					case 'blank' :
						//dump($item_info_detail[1]);
						$data = R('Admin/Blank/get_item_edit',array($item_info_detail[1]));
						$data["question"] = $this->filterHtml($data["question"]);
						break;
					case 'affix' :
						//dump($item_info_detail[1]);
						$data = R('Admin/Affix/get_item_edit',array($item_info_detail[1]));
						break;
					default :
						$data = array();
				}
				//dump($data);
				if(!empty($data)) {
					$item_info[$key] = array('item_type' => $item_info_detail[0], 'item_id' => $item_info_detail[1], 'item_data' => $data);
				}
			}
			$test_data['item_list'] = $item_info;
				
				
		}
		$this->assign('test_data', $test_data);
		//dump($test_data);
		//获得问卷基本信息
		//dump($this->get_form_info($this->_request('formid')));
		$this->assign('question_info', $this->get_form_info($this->_request('formid')));
		$this->display();
	}
	
	/**
	 * 问卷预览界面
	 */
	public function view() {
		$model = new FormModel();
	
		$formid = $this->_request('formid');
		$page = $this->_request('page');
		if(empty($page)) { //用户第一次打开问卷
			//更新用户开始时间
			$groups_user = new GroupsUserModel();
			$userid = $groups_user->getUserId();
			$save_data['begin_time'] = $groups_user->getDate();
			$save_data['ip'] = $groups_user->getIP();
			$groups_user->where("id = '".$groups_user->getUserId()."' and (begin_time is null or begin_time = '')")->setField($save_data);
			$page = $groups_user->where("id = '".$groups_user->getUserId()."'")->getField("page");
			if($page < 0) {
				$page = 0;
			}
			$_GET['page'] = $page;
		}
		//dump($formid); 
		$this->assign("formid", $formid);
		$test_data = $model->field('id, 
									title, 
									intro, 
									item_info, 
									status')
						   ->where("id = '".$formid."'")
						   ->find();
		if(empty($test_data)) {
			$this->error('该问卷不存在！');
		}
		//查询该问卷逻辑设置所涉及的题目
		$logic = new LogicModel();
		$question_logic = $logic->where("formid = '".$formid."' and itemid is not null")->getField("questionid", true);
		$count = 0;
		$show_question_string = '';
		$mutual_string = '';
		$verify_string = '';
		if(!empty($test_data['item_info'])) {
			$item_info = array();
			$item_info = explode(',', $test_data['item_info']);
			foreach($item_info as $key => $value) {
				//根据模块类型获取模块内容
				$item_info_detail = explode(':', $value);
//				dump($item_info_detail);
				if($key < $page * C('PAGESIZE')) continue;
				if($key >= ($page + 1) * C('PAGESIZE')) {// && !in_array($item_info_detail[1], $question_logic)
					$logic_data = $logic->table("question_test_select a,
												 question_test_select_item b,
												 logic c")
										->where("a.id = b.selectid
											 and b.id = c.itemid
											 and c.questionid = '".$item_info_detail[1]."'
											 and a.id in (".$show_question_string.")")
										->select();
					if(empty($logic_data)) {
						continue;
					}
				}
				if(empty($show_question_string)) {
					$show_question_string = "'".$item_info_detail[1]."'";
				} else {
					$show_question_string .= ",'".$item_info_detail[1]."'";
				}
				switch ($item_info_detail[0]) {
					case 'select' :
						//dump($item_info_detail[1]);
						$data = R('Admin/QuestionTestSelect/get_item_edit', array($item_info_detail[1]));
//						dump($data);
						//$data["question"] = $this->filterHtml($data["question"]);
						//多选题如果有，添加项内逻辑控制
						if($data['type'] == 'b') {  //如果是多选
							//遍历所有选项，如果有项内互斥，则添加控制
							$mutual_string .= '$(".class_'.$item_info_detail[1].'").change(function() { var obj = "";';
							foreach($data['item_list'] as $value) {
								if($value['is_mutual'] == 'b') {  //如果是项内互斥
									//添加项内互斥控制
									$mutual_string .= 'if($("#'.$value['id'].'").is(":checked") && "'.$value['is_mutual'].'" == "b") {
															obj = $("#'.$value['id'].'").parents("#'.$item_info_detail[1].'").find("input[type=checkbox]");
															$(obj).each(function() {
																if($(this).attr("id") != "'.$value['id'].'") {
																	this.checked = false;
																} else {
																	alert("您已选中项：'.$value['intro'].'，不能再选择其他项！");
																}
															});
														}';
								}
							}
							$mutual_string .= '});';
//							dump($verify_string);
//								exit;
						}
						break;
					case 'desc' :
						//dump($item_info_detail[1]);
						$data = R('Admin/QuestionTestDesc/get_item_edit',array($item_info_detail[1]));
						break;
					case 'judge' :
						//dump($item_info_detail[1]);
						$data = R('Admin/QuestionTestJudge/get_item_edit',array($item_info_detail[1]));
						break;
					case 'blank' :
						//dump($item_info_detail[1]);
						$data = R('Admin/Blank/get_item_edit',array($item_info_detail[1]));
						//$data["question"] = $this->filterHtml($data["question"]);
						break;
					case 'affix' :
						//dump($item_info_detail[1]);
						$data = R('Admin/Affix/get_item_edit',array($item_info_detail[1]));
						break;
					default :
						$data = array();
				}
				//dump($data);
				if(!empty($data)) {
					$item_info[$key] = array('item_type' => $item_info_detail[0], 'item_id' => $item_info_detail[1], 'item_data' => $data);
				}
				$count++;
			}
			if($count < $page) {
				$this->assign("ops", "commit");
				$this->assign("tips", "提交问卷");
			} else {
				$this->assign("ops", "save");
				$this->assign("tips", "下一页");
			}
			//特殊教师问卷处理吗，因为最后几道题是隐藏的，第四页已经答完，不用第五页
//			if($_REQUEST['formid'] == 'cms_def_webid_20160908165858_1j344gnk95e' && $_REQUEST['page'] == 4) {
//				$this->assign("ops", "commit");
//				$this->assign("tips", "提交问卷");
//			}
			$test_data['item_list'] = $item_info;
		}
		$this->assign('mutual_string', $mutual_string);
		$this->assign('test_data', $test_data);
		//dump($test_data);
		//获得问卷基本信息
		//dump($this->get_form_info($this->_request('formid')));
		$this->assign('question_info', $this->get_form_info($this->_request('formid')));
		//获取问卷逻辑项
		$logic = new LogicModel();
		$logic_data = $logic->table("logic a")
							->join("blank b on a.questionid = b.id")
							->field("a.itemid,
									 a.questionid,
									 b.id blankid")
							->where("a.formid = '".$formid."'
								 and a.itemid is not null")
							->order("a.questionid")
							->select();
		$hide_string = '';
		$questionid = '';
		$tips = '';
		$pre_questionid = '';
		$item_string = '';
		foreach($logic_data as $key => $value) {
			//隐藏所有被逻辑控制项
			$hide_string .= '$("#'.$value['questionid'].'").hide();$("#'.$questionid.'").find("input:first").removeAttr("datatype").removeAttr("nullmsg").removeAttr("error");';
			//添加题项逻辑控制
			if($questionid != $value['questionid']) {
				if(!empty($item_string)){
					$verify_string .= 'if('.$item_string.') {
											$("#'.$questionid.'").show("fast");
											$("#'.$questionid.'").find("input:first").attr("datatype", "*").attr("nullmsg", "'.$tips.'");
										} else {
											$("#'.$questionid.'").hide("fast");
											$("#'.$questionid.'").find("input").removeAttr("datatype").removeAttr("nullmsg");
										}';
				}
				$item_string = '$("#'.$value['itemid'].'").is(":checked")';
				$questionid = $value['questionid'];
				$tips = empty($value['blankid']) ? "请选择" : "请填写";
			} else {
				//说明一个问题被多个选项控制，遍历所有选项
				if(empty($item_string)){
					$item_string = '$("#'.$value['itemid'].'").is(":checked")';
				} else {
					$item_string .= ' || $("#'.$value['itemid'].'").is(":checked")';
				}
				continue;
			}
		}
		//拼接最后一项
		if(!empty($item_string)){
			$verify_string .= 'if('.$item_string.') {
									$("#'.$questionid.'").show("fast");
									$("#'.$questionid.'").find("input:first").attr("datatype", "*").attr("nullmsg", "'.$tips.'");
								} else {
									$("#'.$questionid.'").hide("fast");
									$("#'.$questionid.'").find("input").removeAttr("datatype").removeAttr("nullmsg");
								}';
		}
		$this->assign('hide_string', $hide_string);
		$this->assign('verify_string', $verify_string);
		$bcjs_id = $groups_user->where("id = '".$groups_user->getUserId()."'")->getField("bcjsid");
		$bcjs_xx = $groups_user->field("real_name,get_field_dict_name('groups_user','gender',gender) gender,get_colledge_name(college) college, get_field_dict_name('teacher', 'type', profession) profession")->where("id = '".$bcjs_id."'")->find();
		$this->assign('bcjs_xx', $bcjs_xx);
		$this->display();
	}
	
	/**
	 * 调查结果保存
	 */
	public function itemValue() {
		$formid = $this->_request('formid');
		$ops = $this->_request('ops');
		$page = $this->_request('page') + 1;
		$affixModel = new AffixModel();
		$model = new ItemValueModel();
		$model->startTrans();
		$item_data = array_merge($_REQUEST,$_FILES);
		
		//dump($item_data);
		foreach($item_data as $key => $row) {
			$itemid = explode(':', $key);
			$flag = 'add';
			$save_data = array();
			if(count($itemid) >= 2) {
				$save_data['formid'] = $_REQUEST['formid'];
				$save_data['operator'] = $model->getUserId();
				$save_data['update_date'] = $model->getDate();
				switch($itemid[0]){
					case 'select':
						if($itemid[1] == 'a') {
							$save_data['type'] = 'select';
							$save_data['itemid'] = $itemid[2];
							$save_data['value'] = $row;
						} else if($itemid[1] == 'b') {
							$save_data['itemid'] = $itemid[2];
							foreach ($row as $k => $v){
								$save_data['value'] = $v;
								if(false === $model->add($save_data)) {
									$model->rollback();
									$this->error("多选题失败".$model->getError());
								}
								unset($save_data['value']);
							}
							$flag = 'continue';
						} 
						//dump($save_data);
						break;
					case 'blank':
						$save_data['type'] = 'blank';
						$save_data['itemid'] = $itemid[1];
						$save_data['value'] = $row;
						//dump($save_data);
						break;
					case 'affix':
						$save_data['type'] = 'affix';
						$save_data['questionid'] = $itemid[1];
						$save_data['itemid'] = $itemid[1];
						$affix_data = $affixModel->field("ext,size")->where("id  = '".$itemid[1]."' ")->find();
						$allowExts = str_replace(",,", ",", strtolower($affix_data['ext']));
						$allowExts = explode(',', $allowExts);
						$maxSize = $affix_data['size'] * 1024;
						$file = $row;
						if(!empty($file['name'])) {
							try {
								import("ORG.Net.UploadFile");
								$upload = new UploadFile();	// 实例化上传类
								$upload->maxSize = $maxSize;
								$upload->savePath = C('Affix_UPLOAD_PATH').$formid.'/';
								$upload->allowExts = $allowExts;
								$upload->saveRule = uniqid; //设置上传文件的保存规则
								$upload->supportMulti = false;
								//dump($upload);
								if(!($info = $upload->uploadOne($_FILES[$key], $upload->savePath))) {// 上传错误提示错误信息
									$this->error('附件上传失败：'.$upload->getErrorMsg());
								} else {
									//保存表单数据
									$save_data['value'] = substr($info[0]['savepath'].$info[0]['savename'], 2);
									unset($info);
								}
							} catch(Exception $e) {
								$model->rollback();
								echo $e->getMessage();
							}
						}
						//dump($save_data);
						break;
				}
				if($flag == 'add' && !empty($save_data['value']) ) {
					//验证用户登录
					if(empty($save_data['operator'])) {
						$this->error("你没有登录或者登录信息已丢失，请重新登录。", __APP__);
					}
					$exitsid = $model->where("operator = '".$model->getUserId()."' and itemid = '".$save_data['itemid']."'")->getField("id");
					if(!empty($exitsid)) {
						$model->where("id = '".$exitsid."'")->delete();
					}
					if(false === $model->add($save_data)) {
						$model->rollback();
						$this->error("问卷提交失败".$model->getError());
					}
				}
				unset($save_data);
			}
		}
		$model->commit();
		$groups_user = new GroupsUserModel();
		if($ops == 'commit') {
			//更新用户结束时间
			$save_data['end_time'] = $groups_user->getDate();
			$save_data['page'] = -1;
			$groups_user->where("id = '".$groups_user->getUserId()."'")->setField($save_data);
			$this->success("恭喜你，问卷提交成功。<br/>最后一步，请填写问卷反馈吧，您的反馈对我们很重要哦。", __APP__."?g=Index&m=Index&a=feedback");
		} else {
			//更新用户问卷页码
			$groups_user->where("id = '".$groups_user->getUserId()."'")->setField('page', $page);
			$this->redirect(__APP__."?g=Index&m=Form&a=View&formid=".$formid."&ops=".$ops."&page=".$page);
		}
	}
	
	/**
	 * 
	 */
	public function logic(){
		$map['formid'] = $this->_request('formid');
		$map['itemid'] = $this->_request('itemid');
		
		$model = new LogicModel();
		$next = $model->where($map)->getField('questionid',true);
		$this->ajaxReturn('','','');
	}
	
}
	
?>